//
//  ClubHiddenBavWebViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/26.
//

import UIKit
import WebKit

class ClubHiddenBavWebViewController: ClubBaseViewController {

    var urlString: String? {
        didSet {
            var webUrl: URL?
            if let url = URL(string: urlString ?? "") {
                webUrl = url
            }
            guard let webUrl else { return }
            
            WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { recods in
                recods.forEach{
                    WKWebsiteDataStore.default().removeData(ofTypes: $0.dataTypes, for: [$0]) { }
                }
            }
            ToastUtil.show()
            webView.load(URLRequest(url: webUrl))
        }
    }
    
    var titleName: String? {
        didSet {
            guard let name = titleName else { return }
            titleLabel.text = name
        }
    }
    
    private lazy var webView: WKWebView = {
        let contentController = WKUserContentController()
        let configuration = WKWebViewConfiguration()
        configuration.userContentController = contentController
        let view = WKWebView(frame: .zero, configuration: configuration)
        view.navigationDelegate = self
        view.uiDelegate = self
        // 禁止缩放手势
        let source: String = "var meta = document.createElement('meta');" +
        "meta.name = 'viewport';" +
        "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" +
        "var head = document.getElementsByTagName('head')[0];" + "head.appendChild(meta);";
        let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        view.configuration.userContentController.addUserScript(script)
        
//        view.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        view.scrollView.backgroundColor = .clear
        return view
    }()
    
    private let navView = c_make_ex(UIView.self)
        .bgColor(.white).end()
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#17181A").font(18.font_semiBold).end()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews {
            webView
            navView
            backButton
            titleLabel
        }
        webView.fillContainer().bottom(.safe_bottom)
        navView.leading(0).top(0).width(.screenWidth).height(.navi_height)
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.width(.screenWidth - 100.0).leading(56)
        titleLabel.CenterY == backButton.CenterY
        
        backButton.addTarget(self, action: #selector(clickWebViewBackButton), for: .touchUpInside)
    }
    
    @objc private func clickWebViewBackButton(){
        if !webView.canGoBack {
            self.navigationController?.popViewController(animated: true)
        }else{
            webView.goBack()
        }
    }
}

//MARK: - WKNavigationDelegate
extension ClubHiddenBavWebViewController: WKNavigationDelegate {
    
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
    
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
    }
    
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        ToastUtil.dismiss()
        if self.titleName == nil || (self.titleName ?? "").isEmpty {
            self.titleName = self.webView.title
        }
    }
    
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        
    }
    
    // 接收到服务器跳转请求之后调用
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        
    }
    
    // 在收到响应后，决定是否跳转 -> 默认允许
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    // 在发送请求之前，决定是否跳转 -> 默认允许
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
        decisionHandler(.allow, preferences)
    }
}

//MARK: - WKUIDelegate, WKScriptMessageHandler
extension ClubHiddenBavWebViewController: WKUIDelegate, WKScriptMessageHandler {
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
    
    @objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alertController = UIAlertController(title: "Tips", message: message, preferredStyle: .alert)
        let actionOk = UIAlertAction(title: "OK", style: .default) { alert in
            completionHandler()
        }
        alertController.addAction(actionOk)
        present(alertController, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alertController = UIAlertController(title: "Tips", message: message, preferredStyle: .alert)
        let actionOk = UIAlertAction(title: "OK", style: .default) { alert in
            completionHandler(true)
        }
        let actionCancel = UIAlertAction(title: "Cancel", style: .default) { alert in
            completionHandler(false)
        }
        alertController.addAction(actionOk)
        alertController.addAction(actionCancel)
        present(alertController, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        completionHandler("")
    }
    
}
